﻿using HomagChina.CCHCS;
using HomagChina.CCHCS.DataTypeModel;
using HomagChina.CCHCS.Views;
using HomagChina.CCHS.ViewModels;
using HomagChina.CCHS.Views;
using HomagGroup.Base.UI;
using HomagGroup.BaseUI.Router;
using Proxy;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Threading;
using static HomagChina.CCHCS.ProcessResourceInternal;

namespace HomagChina.CCHCS.ViewModels
{
    public class HomeViewModel : HomagGroup.Base.UI.NotifyPropertyChangedBase
    {
        #region Command

        public RelayCommand ClickInFeed { get; }

        public RelayCommand ClickOutFeed { get; }
        public RelayCommand ClickCancelAll { get; }
        public RelayCommand ClickRunEmpty { get; }
        public RelayCommand UnLoadedCommand { get; }
        public RelayCommand LoadedCommand { get; }

        #endregion Command

        #region Handle

        private SearchInfoHandle Handle_Search;
        private ModifyInfoHandle Handle_Modify;

        #endregion Handle

        #region Conponents

        private DispatcherTimer UpdateSessionTimer_canvas;
        private ContainersCreator CanvasContainer;
        private LayerCreator CanvasLayer;
        private ObservableCollection<TaskInfoModel> _List_TaskInfoModel;

        public ObservableCollection<TaskInfoModel> List_TaskInfoModel
        {
            get => _List_TaskInfoModel;
            set { _List_TaskInfoModel = value; OnPropertyChanged(); }
        }

        private DeviceState _InFeedState;

        public DeviceState InFeedState
        {
            get => _InFeedState;
            set { _InFeedState = value; OnPropertyChanged(); }
        }

        private DeviceState _OutFeedState;

        public DeviceState OutFeedState
        {
            get => _OutFeedState;
            set { _OutFeedState = value; OnPropertyChanged(); }
        }

        private DeviceState _PlcState;

        public DeviceState PlcState
        {
            get => _PlcState;
            set { _PlcState = value; OnPropertyChanged(); }
        }

        private bool _InFeedCheck;

        public bool InFeedCheck
        {
            get => _InFeedCheck;
            set { _InFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _InFeedEnable = true;

        public bool InFeedEnable
        {
            get => _InFeedEnable;
            set { _InFeedEnable = value; OnPropertyChanged(); }
        }

        private bool _OutFeedCheck;

        public bool OutFeedCheck
        {
            get => _OutFeedCheck;
            set { _OutFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _OutFeedEnable = true;

        public bool OutFeedEnable
        {
            get => _OutFeedEnable;
            set { _OutFeedEnable = value; OnPropertyChanged(); }
        }

        private bool _RunEmptyCheck;

        public bool RunEmptyCheck
        {
            get => _RunEmptyCheck;
            set { _RunEmptyCheck = value; OnPropertyChanged(); }
        }

        #endregion Conponents

        public event EventHandler RequestScrollPositionSave;

        public event EventHandler RequestScrollPositionRestore;

        #region 属性

        private Canvas _Containers = new Canvas();

        public Canvas Containers
        {
            get => _Containers;
            set { _Containers = value; OnPropertyChanged(); }
        }

        private Canvas _Layer = new Canvas();

        public Canvas Layer
        {
            get => _Layer;
            set { _Layer = value; OnPropertyChanged(); }
        }

        private ObservableCollection<Proxy.LayerInfo> _BoardsInContainerList;

        public ObservableCollection<Proxy.LayerInfo> BoardsInContainerList
        {
            get => _BoardsInContainerList;
            set { _BoardsInContainerList = value; OnPropertyChanged(); }
        }

        #endregion 属性
        ExcelDataReader excelDataReader = new ExcelDataReader();
        public HomeViewModel()
        {
            UIAdjustments.CurrentThreadLanguageManager.CultureChanged += NavigateServices.Instance.LanguageManagerCultureChanged;

            Handle_Search = new SearchInfoHandle();
            Handle_Modify = new ModifyInfoHandle();

            ClickInFeed = new RelayCommand(ClickInFeedCommand);
            ClickOutFeed = new RelayCommand(ClickOutFeedCommand);
            ClickCancelAll = new RelayCommand(ClickCancelAllCommand);
            ClickRunEmpty = new RelayCommand(ClickRunEmptyCommand);
            LoadedCommand = new RelayCommand(ViewloadedCommand);
            UnLoadedCommand = new RelayCommand(ViewUnloadedCommand);

            BoardsInContainerList = excelDataReader.BoardsList;//new ObservableCollection<LayerInfo>();
            CanvasContainer = new ContainersCreator();//Containers
            CanvasContainer.Init(_Containers, BoardsInContainerList);
            CanvasLayer = new LayerCreator(Layer);
            CanvasContainer.LayerSelectedEventHandler += OnlayerSelected;

            UpdateSessionTimer_canvas = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(1000)
            };
        }

        public void HandleOpenBatchDetail()
        {
            BatchListDialogViewModel batchListDialogViewModel = new BatchListDialogViewModel();
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<BatchListDialog>(batchListDialogViewModel, null);
        }

        /// <summary>
        /// 页面加载
        /// </summary>
        private void ViewloadedCommand()
        {
            RefreshUI();
        }

        /// <summary>
        /// Unloade
        /// </summary>
        private void ViewUnloadedCommand()
        {
            UpdateSessionTimer_canvas.Stop();
        }

        public void RefreshUI()
        {
            Random random = new Random();
            UpdateSessionTimer_canvas.Tick += (sender, args) =>
            {
                UpdateSessionTimer_canvas.Dispatcher.BeginInvoke(new Action(() =>
                {
                    //var infosCount = Handle_Search.GetStorageCount();
                    //if (infosCount != count)
                    //{
                    //    BoardsInContainerList = Handle_Search.GetStorageInfo();
                    //    CanvasContainer.Init(Containers, BoardsInContainerList);//Containers,
                    //}

                    excelDataReader.BoardsList.Add(new LayerInfo()
                    {
                        Boardcode = "GZZHCS_10001",
                        Length = random.Next(500, 1000),
                        Width = random.Next(300, 500),
                        Thickness = 18,
                        CalCenterX = random.Next(0, 500),
                        RSCenterY = random.Next(0, 300),
                        RSShelfOrder = random.Next(1, 5),
                        RSLayerNum = random.Next(1, 21),
                        PackRt90 = false,
                        ZCoor = 0
                    });

                    BoardsInContainerList = excelDataReader.BoardsList;
                    CanvasContainer.Init(Containers, BoardsInContainerList);

                    if (_sender != null)
                    {
                        DrawLayers();
                    }
                }));
            };
            UpdateSessionTimer_canvas.Start();
        }

        object _sender;
        /// <summary>
        /// 层级选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnlayerSelected(object sender, EventArgs e)
        {
            _sender = sender;
            DrawLayers();
        }

        void DrawLayers()
        {
            var s = BoardsInContainerList.Where(x => x.RSShelfOrder.ToString() == ((_sender as Canvas).Parent as Canvas).Uid && x.RSLayerNum.ToString() == (_sender as Canvas).Uid).ToList();
            CanvasLayer.DrawLayers(s);
        }

        #region Infeed

        /// <summary>
        /// 入库功能开启
        /// Open the infeed function
        /// </summary>
        public void ClickInFeedCommand()
        {
            if (this.InFeedCheck)
            {
                ActivatedInfeed();
            }
            else
            {
                UnactivatedInfeed();
            }
        }

        public void ActivatedInfeed()
        {
            this.InFeedCheck = true;
            this.InFeedState = DeviceState.Ok;
            this.InFeedEnable = !RunEmptyCheck;
            Globle.isInfeedActive = true;
        }

        public void UnactivatedInfeed()
        {
            this.InFeedCheck = false;
            this.InFeedState = DeviceState.Off;
            this.InFeedEnable = !RunEmptyCheck;
            Globle.isInfeedActive = false;
        }

        #endregion Infeed

        #region Outfeed

        /// <summary>
        /// 出库功能开启
        /// Open the outfeed function
        /// </summary>
        public void ClickOutFeedCommand()
        {
            if (this.OutFeedCheck)
            {
                ActivatedOutfeed();
            }
            else
            {
                UnactivatedOutfeed();
            }
        }

        public void ActivatedOutfeed()
        {
            this.OutFeedCheck = true;
            this.OutFeedState = DeviceState.Ok;
            this.OutFeedEnable = !RunEmptyCheck;
            Globle.isOutfeedActive = true;
        }

        public void UnactivatedOutfeed()
        {
            this.OutFeedCheck = false;
            this.OutFeedState = DeviceState.Off;
            this.OutFeedEnable = !RunEmptyCheck;
            Globle.isOutfeedActive = false;
        }

        #endregion Outfeed

        #region Cancel All

        /// <summary>
        /// 取消所有功能点击事件
        /// Cancel all function
        /// </summary>
        public void ClickCancelAllCommand()
        {
            CancelAll();
        }

        /// <summary>
        /// 取消所有功能
        /// </summary>
        public void CancelAll()
        {
            UnactivatedRunEmpty();
            UnactivatedInfeed();
            UnactivatedOutfeed();
        }

        #endregion Cancel All

        #region Run Empty

        /// <summary>
        /// 清空线体所有板件
        /// Empty all the parts of the line
        /// </summary>
        public void ClickRunEmptyCommand()
        {
            ActivatedInfeed();
            ActivatedOutfeed();

            //if (RunEmptyCheck)
            //{
            //    Utility.Globle.isRunEmptyActive = true;
            //    Task.Factory.StartNew(async () =>
            //    {
            //        string callBackMsg = await Handle_RunEmpty.RunEmpty();
            //        CancelAll();
            //        HomagGroup.Base.UI.Windows.MessageBox.Show(LocalizedText.CreateFromResourceManager(HomagChina.Basic.CCT.ResourceLibrary.Properties.Resources.ResourceManager, callBackMsg).ToString());
            //    });
            //}
            //else
            //{
            //    Utility.Globle.isRunEmptyActive = false;
            //}
        }

        /// <summary>
        ///
        /// </summary>
        public void UnactivatedRunEmpty()
        {
            RunEmptyCheck = false;
            //Utility.Globle.isRunEmptyActive = false;
        }

        #endregion Run Empty
    }
}